//
//  SLBackMsgViewModel.m
//  StarLight
//
//  Created by Duke.wu on 16/6/7.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLBackMsgViewModel.h"
#import "NSDate+Utils.h"
#import "UUMessage.h"
#import "UUMessageFrame.h"
#import "SLNetWork.h"


@interface SLBackMsgViewModel ()

@property (nonatomic, strong) NSString *requstPath;

@end

@implementation SLBackMsgViewModel

- (instancetype)init{
  self = [super init];
  if(self){
    NSString *uid = [DEFAULTS objectForKey:loginInfo][@"id"];
    self.requstPath = [NSString stringWithFormat:@"%@/sys/backlist?uid=%@",baseUrl,uid];
    [self addObservers];
  }
  return self;
}

- (void)addObservers{
  [[RACObserve(self, requstPath) filter:^BOOL(id value) {
    return value != nil;
  }] subscribeNext:^(NSString *path) {
    
    
    [SLNetWork getDataWithRequest:path complete:^(id respond, NSError *error) {
      if (!error) {
        NSMutableArray *listArr = [NSMutableArray arrayWithCapacity:1];
        NSMutableArray *arr = [SLBckMsgModel mj_objectArrayWithKeyValuesArray:respond[@"data"]];
        
        for (int i = 0; i < arr.count; i ++) {
          SLBckMsgModel *model = arr[i];
          UUMessageFrame *messageFrame = [[UUMessageFrame alloc]init];
          UUMessage *message = [[UUMessage alloc] init];
          [message setWithModel:model];
          [message minuteOffSetStart:previousTime end:model.time];
          messageFrame.showTime = message.showDateLabel;
          [messageFrame setMessage:message];
          [listArr addObject:messageFrame];
        }
         self.backMsgList = listArr;
      };
    }];
  }];
  
  
}


- (NSMutableArray *)backMsgList{
  if (!_backMsgList) {
    _backMsgList = [NSMutableArray arrayWithCapacity:1];
  }
  return  _backMsgList;
}


// 添加聊天item（一个cell内容）
static NSString *previousTime = nil;

// 添加自己的item
- (void)addSpecifiedItem:(SLBckMsgModel *)model
{
  UUMessageFrame *messageFrame = [[UUMessageFrame alloc]init];
  UUMessage *message = [[UUMessage alloc] init];
  

  [message setWithModel:model];
  [message minuteOffSetStart:previousTime end:model.time];
  messageFrame.showTime = message.showDateLabel;
  [messageFrame setMessage:message];
  
  if (message.showDateLabel) {
    previousTime = model.time;
  }
  [self.backMsgList addObject:messageFrame];
  [self backToServiceWithModel:model];

}


- (void)first{
  NSString *uid = [DEFAULTS objectForKey:loginInfo][@"id"];
  self.requstPath = [NSString stringWithFormat:@"%@/sys/backlist?uid=%@",baseUrl,uid];
}


- (void)backToServiceWithModel:(SLBckMsgModel *)model{
  @weakify(self)
  NSString *postUrl = [NSString backUrlWithService:@"sys" methodName:@"backmsg"];
  NSDictionary *para = @{@"uid":[DEFAULTS objectForKey:loginInfo][@"id"],@"content":model.content};
  [SLNetWork postDataWithParameters:para postUrl:postUrl complete:^(id respond, NSError *error) {
    @strongify(self)
    [self first];
  }];
}



@end




@implementation SLBckMsgModel


@end
